//
//  MusicCustomViewModel.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/26.
//

import UIKit

class MusicCustomViewModel {
    let createSuccessSubject = PublishSubject<String>()
    let reloadListSubject = PublishSubject<Void>()
    var stlyeList:[MusicStyle] = []
    
    var music_name:String?
    var music_lyric:String?
    var style_text:String?
    var is_instrumental:Bool = false
    
    func generateLyric(){
        guard let desc = music_lyric else {
            NDProgressHUD.show(message: "请输入歌词后再优化")
            return
        }
        kHideKeyboard()
        NDProgressHUD.showLoading()
        RequestService.instance.createLyric(lyric_desc: desc) { desc in
            NDProgressHUD.hide()
            self.music_lyric = desc
            self.reloadListSubject.onNext(())
        } failureClosure: { error in
            NDProgressHUD.show(message: error ?? "")
        }
    }
    
    func RandomStyle(){
        NDProgressHUD.showLoading()
        RequestService.instance.RandomStyle { style in
            NDProgressHUD.hide()
            self.appendStyle(style)
        }
    }
    
    func getStyleList() {
        NDProgressHUD.showLoading()
        RequestService.instance.requestStyle { styleList in
            NDProgressHUD.hide()
            self.stlyeList = styleList
            self.reloadListSubject.onNext(())
        }
    }
    
    
    func musicCreate() {
        let lyrics: String
        if is_instrumental {
            lyrics = ""
        } else if let musicLyric = self.music_lyric, !musicLyric.isEmpty {
            lyrics = musicLyric
        } else {
            NDProgressHUD.show(message: "请输入歌词")
            return
        }
        guard let musicName = self.music_name, !musicName.isEmpty else {
            NDProgressHUD.show(message: "请输入标题")
            return
        }
        
        let instrumental = is_instrumental ? 1 : 0
        let styleText = self.style_text ?? ""
        NDProgressHUD.showLoading()
        RequestService.instance.music_create(name: musicName, type: 2, lyrics: lyrics, lyric_desc: "", style_text: styleText, is_instrumental: instrumental) { [weak self] checkId in
            NDProgressHUD.hide()
            self?.createSuccessSubject.onNext(checkId)
        } failureClosure: { error in
            NDProgressHUD.show(message: error ?? "")
        }
    }
    
    func appendStyle(_ style: String) {
//        if self.style_text?.isEmpty ?? true {
//            // 如果 style_text 为空，则直接赋值
//            self.style_text = style
//        } else {
//            // 如果 style_text 不为空，则在前面添加逗号
//            self.style_text?.append(",\(style)")
//        }
        self.style_text = style
        
        self.reloadListSubject.onNext(())

    }
}
